﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yipusoft.BaseDoc;
using System.IO;
using SmartWeb.BLL;

public partial class Task_BaseDoc_BaseDocEdit : System.Web.UI.Page
{
    BaseDocDataContext db = new BaseDocDataContext();
    private List<string> listName = new List<string>();
    private List<string> listEx = new List<string>();
    private List<string> listTitle = new List<string>();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            init();
            BindData();
        }
    }

    private void BindData()
    {
        BaseDocs doc = Doc.GetBaseDoc(Request["ID"]);
        this.txtCaption.Text = doc.Caption;       
        this.DptMonth.SelectedValue = doc.CreateDate.Value.Month.ToString();
        this.DptYear.SelectedValue = doc.CreateDate.Value.Year.ToString();
        ddlClass.SelectedValue = doc.TID.Value.ToString();
        this.txtAddress.Text = doc.Contents;
        BaseDocType objType=Doc.GetDocType(doc.TID.Value);
        if (objType.ParentID.Value != 0)
        {
            ddlType.SelectedValue = objType.ParentID.Value.ToString();
            BindClass();
            ddlClass.Visible = true;
            ddlClass.SelectedValue = doc.TID.Value.ToString();

        }
        else
        {
            ddlType.SelectedValue = objType.ID.ToString();
        }
        BindFileList();

        SetControl();
    }

    private void BindFileList()
    {
        this.dltList.DataSource = Doc.GetBaseDocFileByDID(Request["ID"]);
        this.dltList.DataBind();
    }
    private void init()
    {
        BindType();
        BindDateList();
        if (Request.QueryString["ID"] == null)
        {
            Caption.Text = "新增档案";
        }
        else
        {
            Caption.Text = "修改档案";
        }

    }

    private void BindDateList()
    {
        for (int i = 2008; i <= 2050; i++)
        {
            ListItem li = new ListItem();
            li.Text = i.ToString() + "年";
            li.Value = i.ToString();
            DptYear.Items.Add(li);
        }
        for (int i = 1; i <= 12; i++)
        {
            this.DptMonth.Items.Add(new ListItem(i.ToString() + "月", i.ToString()));
        }
        DptMonth.SelectedValue = DateTime.Now.Month.ToString();
        DptYear.SelectedValue = DateTime.Now.Year.ToString();
    }

    private void BindType()
    {
        ddlType.DataSource = db.BaseDocType.Where<BaseDocType>(o => o.ParentID == 0);
        ddlType.DataBind();
        BindClass();
    }

    private void BindClass()
    {
        if (ddlType.SelectedValue=="")
            return;
 
        ddlClass.DataSource = db.BaseDocType.Where<BaseDocType>(o => o.ParentID == Convert.ToInt32(ddlType.SelectedValue));
        ddlClass.DataBind();
        if (ddlClass.Items.Count == 0)
        {
            ddlClass.Visible = false;
        }
        else
        {
            ddlClass.Visible = true;
        }
    }

    private int GetDID()
    {
        if (ddlClass.Visible)
            return int.Parse(ddlClass.SelectedValue);
        else
            return int.Parse(ddlType.SelectedValue);
    }

    //多文件上传
    private Boolean SaveImages()
    {
        ///'遍历File表单元素
        HttpFileCollection files = HttpContext.Current.Request.Files;

        /// '状态信息
        System.Text.StringBuilder strMsg = new System.Text.StringBuilder();
        strMsg.Append("上传的文件分别是：<hr color=red>");
        //try
        //{
            for (int iFile = 0; iFile < files.Count; iFile++)
            {
                ///'检查文件扩展名字
                HttpPostedFile postedFile = files[iFile];
                string fileName, fileExtension, fileTitle;
                fileTitle = System.IO.Path.GetFileName(postedFile.FileName);
                if (fileTitle != "")
                {
                    fileExtension = System.IO.Path.GetExtension(fileTitle);
                    string DepartmentID = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID;
                    string mapPath = "~/Document/" + DepartmentID + "/";
                    fileName = System.Web.HttpContext.Current.Request.MapPath(mapPath);                                      
                    if (!Directory.Exists(fileName))
                    {
                        Directory.CreateDirectory(fileName);
                    }
                    //fileName += fileTitle;
                    ///'可根据扩展名字的不同保存到不同的文件夹
                    ///注意：可能要修改你的文件夹的匿名写入权限。
                    string temp = DateTime.Now.ToString("yyMMddhhmmss") + iFile.ToString("000") + fileTitle;
                    fileName += temp;                   
                    postedFile.SaveAs(fileName);
                    listEx.Add(fileExtension);
                    listName.Add(temp);
                    listTitle.Add(fileTitle);

                }

            }

            return true;
        //}
        //catch (System.Exception Ex)
        //{
        //    //strStatus.Text = Ex.Message;
        //    return false;
        //}
    }
    #region Web 窗体设计器生成的代码

    protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindClass();

        SetControl();
    }

    private void SetControl()
    {
        if (ddlType.SelectedValue.Equals("3"))
        {
            txtAddress.Visible = true;
            lbladd.Visible = true;
            pn.Visible = false;
            this.dltList.Visible = false;
            this.lbldltlist.Visible = false;
        }
        else
        {
            pn.Visible = true;
        }
        if (ddlType.SelectedValue.Equals("2"))
        {
            txtAddress.Visible = false;
            lbladd.Visible = false;
            pn.Visible = true;

        }
        if (ddlType.SelectedValue.Equals("1"))
        {
            txtAddress.Visible = false;
            lbladd.Visible = false;
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        SaveImages();
        Yipusoft.Account.Model.UserInfo user = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name);
        DateTime dt = new DateTime(int.Parse(DptYear.SelectedValue), int.Parse(DptMonth.SelectedValue), 1);
        BaseDocs doc = new BaseDocs();
        doc.ID = new Guid(Request["ID"]);
        doc.Caption = txtCaption.Text;
        doc.Contents = txtAddress.Text;
        doc.CreateDate = dt;
        doc.Remark = "";
        doc.SetDepartment = user.DepartmentID;
        doc.SetUserID = user.UserID;
        doc.TID = GetDID();
        string dID =Doc.UpdateDoc(doc);        
        if (string.IsNullOrEmpty(dID))
            return;

        for (int i = 0; i < listTitle.Count(); i++)
        {
            Doc.DeleteBaseDocFileByDID(dID);
            Doc.InsertDocFile(dID, listEx[i].ToString(), listName[i].ToString() , listTitle[i].ToString());
        }
        lblPrompt.Text = "操作已成功";
        this.btnAdd.Enabled = false;
        BindFileList();
        
    }
    #endregion
    protected void ibtnDelete_Command(object sender, CommandEventArgs e)
    {
        Doc.DeleteBaseDocFileByID(e.CommandArgument.ToString());
        BindFileList();


    }
    protected void lbtn_Command(object sender, CommandEventArgs e)
    {
        if (e.CommandArgument == null)
            return;
        //try
        //{

            string fileName = e.CommandName.ToString();
            string filePath = Server.MapPath("~/Document/" + Yipusoft.Account.BLL.User.GetUser(User.Identity.Name).DepartmentID+"/"+e.CommandArgument + "");//路径
            //以字符流的形式下载文件
            FileStream fs = new FileStream(filePath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.ContentType = "application/octet-stream";
            //通知浏览器下载文件而不是打开
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();
        //}
        //catch { };
    }

    public string GetButton()
    {
        if (ddlType.SelectedValue.Equals("1"))
            return "<input type='button' value='增加(Add)' onclick='addFile()'>";
        else
            return "";
    }
}
